package com.mayikt.zuul.handler.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Console;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.mayikt.base.BaseResponse;
import com.mayikt.constants.Constants;
import com.mayikt.zuul.feign.VerificaCodeServiceFeign;
import com.mayikt.zuul.handler.BaseHandler;
import com.mayikt.zuul.handler.GatewayHandler;
import com.netflix.zuul.context.RequestContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;

@Service
@Slf4j
public class ApiCheckTokenHandler extends BaseHandler implements GatewayHandler {
    @Autowired
    private VerificaCodeServiceFeign verificaCodeServiceFeign;

    @Override
    public void service(RequestContext rc, String ipAddress, HttpServletResponse response) {
        String servletPath = rc.getRequest().getServletPath();
        log.info(">>>>>servletPath:" + servletPath + ",servletPath.substring(0, 5):" + servletPath.substring(0, 5));
        if (servletPath.substring(0, 7).equals("/public")) {
            String accessToken = rc.getRequest().getParameter("accessToken");
            log.info(">>>>>accessToken验证:" + accessToken);
            if (StrUtil.isEmpty(accessToken)) {
                Console.log("AccessToken cannot be empty");
                this.resultError(rc,"AccessToken cannot be empty");
            }
            // 调用接口验证accessToken是否失效
            BaseResponse<JSONObject> appInfo = verificaCodeServiceFeign.getAppInfo(accessToken);
            log.info(">>>>>>data:" + appInfo.toString());
            if (!appInfo.getCode().equals(Constants.HTTP_RES_CODE_200)) {
                log.info(appInfo.getMsg());
                this.resultError(rc,appInfo.getMsg());
            }
        }
        if (!BeanUtil.isEmpty(this.nextGatewayHandler)){
            this.nextGatewayHandler.service(rc,ipAddress,response);
        }
    }
}
